'use strict';

// const Controller = require('egg').Controller;
const Controller = require('./index');
class TradeController extends Controller {
  async get() {
    var { active, page = 1, limit = 10, title, subcategory, pid, port } = this.ctx.query;
    let res = {}

    active = active > 0 ? active : null
    var data = { // 搜索 post 表
      where: { port, isdel: 0 }, // WHERE 条件
      limit, // 返回数据量
      offset: (page - 1) * 10, // 数据偏移量
    }

    if (active > 0) {
      data.where.grade = active;
    }
    if (pid > -1) {
      data.where.pid = pid;
    }
    if (title) {
      res.data = await this.app.mysql.query(`SELECT * FROM category WHERE title LIKE "%"?"%" LIMIT ?,? and port= ?`, [title, data.offset, data.limit, port]);
    }

    else if (subcategory) {
      res.data = await this.app.mysql.query(`SELECT * FROM category WHERE subcategory LIKE "%"?"%" LIMIT ?,? and port= ?`, [subcategory, data.offset, data.limit, port]);

    }
    else if (title && subcategory) {
      res.data = await this.app.mysql.query(`SELECT * FROM category WHERE subcategory LIKE "%"?"%" and title LIKE "%"?"%" LIMIT ?,? and port= ?`, [subcategory, title, data.offset, data.limit, port]);

    } else {
      res.data = await this.ctx.service.db.getDb('category', data);
      res.total = await this.ctx.service.db.getTotal('category', data);

    }


    res.code = 0;
    this.success(res);
    // this.ctx.body = res;
  }
  async add() {
    var { id, title, pid = 0, grade, describe, port, subcategory, link, isdel = 0 } = this.ctx.request.body;

    var data = { // 搜索 post 表
      id, link, isdel,
      title, pid, grade, describe, port, subcategory
    }
    let res = {}
    if (id)
      await this.ctx.service.db.updataDb('category', data);
    else
      await this.ctx.service.db.addDb('category', data);
    res.code = 0;
    this.ctx.body = res;
  }
}

module.exports = TradeController;
